package com.yds.socket.utils;


import android.text.TextUtils;

import java.nio.charset.StandardCharsets;

/**
 * 作者:     YDS
 * 创建时间: 2023/2/15 13:22
 * 页面描述: 字符串工具
 */
public class SocketBytesUtil {

    /**
     * 检测字符串是否是16进制
     */
    public static boolean checkStringIsHex(String msg) {
        if (TextUtils.isEmpty(msg)) return false;

        // 去掉空格
        if (msg.contains(" ")) {
            msg = msg.replace(" ", "");
        }
        msg = msg.toUpperCase();
        for (int i = 0; i < msg.length(); i++) {
            char c = msg.charAt(i);
            if ((c < '0' || c > '9') && (c < 'A' || c > 'F')) {
                return false;
            }
        }

        return true;
    }

    /**
     * 16进制转10进制
     *
     * @param hex 16进制字符串
     */
    public static int hexToDecimal(String hex) {
        hex = hex.toUpperCase();
        int max = hex.length();
        int result = 0;
        for (int i = max; i > 0; i--) {
            char c = hex.charAt(i - 1);
            int decimal;
            if (c >= '0' && c <= '9') {
                decimal = c - '0';
            } else {
                decimal = c - 55;
            }
            result += Math.pow(16, max - i) * decimal;
        }
        return result;
    }

    /**
     * 字符串-转-字节数组
     */
    public static byte[] convertStringToBytes(String msg) {
        if (TextUtils.isEmpty(msg)) return new byte[0];

        boolean b = checkStringIsHex(msg);
        if (!b) {// 非16进制文字
            return msg.getBytes();
        }

        // 去掉空格
        if (msg.contains(" ")) {
            msg = msg.replace(" ", "");
        }
        char[] hexChars = msg.toCharArray();
        if (msg.length() % 2 != 0)
            return new byte[0];
        byte[] returnBytes = new byte[msg.length() / 2];
        for (int i = 0; i < returnBytes.length; i++) {
            int pos = i * 2;
            returnBytes[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }

        return returnBytes;
    }

    /**
     * char类型转字节
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    /**
     * 字节数组-转-字符串
     *
     * @param value 数组
     */
    public static String convertBytesToString(byte[] value) {
        StringBuilder returnString = new StringBuilder();
        for (byte b : value) {
            String hex = Integer.toHexString(b & 255);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            returnString.append(hex);
        }
        boolean b = checkStringIsHex(returnString.toString());

        if (b) {
            return returnString.toString();
        } else {
            return new String(value, StandardCharsets.UTF_8);
        }
    }

}
